package main.java.indi.zyj.c150.back;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class _09_CombinationSum {

    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    int currentSum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) return res;
        Arrays.sort(candidates);
        backtrack(candidates, target, 0);
        return res;
    }

    private void backtrack(int[] candidates, int target, int start) {
        if (target == currentSum) {
            res.add(new ArrayList<>(path));
            return;
        }
        if (target < currentSum) return;
        for (int i = start; i < candidates.length; i++) {
            currentSum += candidates[i];
            path.addLast(candidates[i]);
            // start重复使用
            backtrack(candidates, target, i);
            path.removeLast();
            currentSum -= candidates[i];
        }
    }


}
